package com.xunua.myaudioandvideolearning.h264Packaging

import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.PersistableBundle
import android.util.Log
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.xunua.myaudioandvideolearning.MainActivity
import com.xunua.myaudioandvideolearning.R
import java.io.File

/**
 * @author: linxunyou
 * @description:简单的录屏
 * @date :2022/5/615:35
 **/
private const val TAG = "PackagingActivity"
class PackagingActivity : AppCompatActivity() {
    private var mMediaProjectionManager:MediaProjectionManager?=null
    private var mIntent:Intent?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_packaging)
        getPermission()
    }


    /**
     * 开始录屏
     */
    fun start(view: View) {
        mMediaProjectionManager = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        var intent = mMediaProjectionManager?.createScreenCaptureIntent()
        startActivityForResult(intent,1)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK || requestCode!=1){
            return
        }else{
            if (data==null) return
            val file = File(Environment.getExternalStorageDirectory().toString() + "/codec.h264")
            if (file.exists()) {
                file.delete()
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                mIntent = Intent(this, ScreenRecorderService::class.java)
                mIntent?.putExtra("resultCode",resultCode)
                mIntent?.putExtra("data",data)
                startForegroundService(mIntent)
            }else{
                //得到录屏权限，进行录屏---》新建h264
                val mediaProjection = mMediaProjectionManager?.getMediaProjection(resultCode, data) ?: return
                var h264Encoder = H264Encoder(mediaProjection)
                h264Encoder.start()
            }
        }
    }

    private fun getPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(
                arrayOf(
                    android.Manifest.permission.READ_EXTERNAL_STORAGE,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    android.Manifest.permission.CAMERA
                ), 1
            )
        }
    }

    fun play(view: View) {
        var intent = Intent(this,MainActivity::class.java)
        startActivity(intent)
    }
}